//axios 封装
import axios from 'axios'
import Vue from 'vue';
import { Message } from 'element-ui';
// axios.defaults.baseURL = process.env.VUE_APP_BASE_API
axios.defaults.timeout = 1000 * 60 //设置接口超时时间
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.interceptors.request.use(
    config => {
        let token = window.sessionStorage.getItem("token");
        if (token) {
            config.headers.common['Authorization'] = token;
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

axios.interceptors.response.use(
    response => {
        /* let {
            data,
            config
        } = response;
        if (response.status === 200 && response.data.code == 2) {
            window.location.href = `${server_path}/#/login`;
            window.sessionStorage.clear();
            Message.error('登录超时了,请重新登录');
        } */
        return response;
    },
    error => {
        //断网处理或者请求超时
        console.log(error)
        if (!error.response) {

            //请求超时
            if (error.message.includes('timeout')) {
                Message.error('请求超时了,请稍后重试')

            } else {
                //断网，可以展示断网组件
                Message.error('请检查网络连接是否正常')
            }
            return
        }
        const status = error.response.status
        switch (status) {
            case 500:
                Message.error('服务器内部错误')
                break;
            case 404:
                Message.error('未找到远程服务器')
                break;
            case 400:
                Message.error("数据异常");
                break
            default:
                Message.error(error.response.data.message);
        }
        return Promise.reject(error)
    }
)

Vue.prototype.$axios = axios;
export default axios;
// 封装动态url
let _hostname;
let _protocol;
let _port;
let _hostname_sess = window.localStorage.getItem('_host');
let _protocol_sess = window.localStorage.getItem('_protocol');
let _port_sess = window.localStorage.getItem('_port');
if (process.env.NODE_ENV == "development") {
    // 开发环境 
    _hostname = '172.17.11.59'; // 172.17.11.59:8861   172.16.35.28:8861 172.16.41.41:8861
    _protocol = 'https:';
    _port = 8861;
} else if (process.env.NODE_ENV == "production") {
    // 生产环境
    _hostname = _hostname_sess ? _hostname_sess : 'localhost';
    _protocol = _protocol_sess ? _protocol_sess : 'https:';
    _port = _port_sess ? _port_sess : 8861;
} 

const url1 = `${_protocol}//${_hostname}:${_port}/`

console.log('设置之后的ip地址是', url1);

export {
    url1
}